let storage = bui.storage();
let language, org, translate;
let ids
loader.define(function(require, exports, module, global) {
    var pageview = {
        init(){
            let qrcodeBase
            let picClass = 'imgBJPC'
            if (isMobile()) {
                picClass = 'imgBJ'
            }
            router.$("#downloadQrcode").show()
            if (isWeiXin()) {
                router.$("#downloadQrcode").hide()
            }
            router.$("#qrcodeHb").hide()

            translate = global.translate
            language = storage.get("language", 0)
            if (!language) {
                language = 'chinese_simplified'
            }

            try {
                translate.selectLanguageTag.show = false;
                translate.ignore.id.push('languageContent')
                let curLanguage = translate.language.getCurrent()
                if (curLanguage !== language) {
                    translate.changeLanguage(language)
                }
                translate.execute();
            }catch (e) {
                console.log("切换语言报错")
            }
            if (language === "chinese_simplified") {
                router.$("#gz").css("font-size", "")
                router.$("#fb").css("font-size", "")
                router.$("#sy").css("font-size", "0.28rem")
                router.$("#name1").css("font-size", "0.28rem")
                router.$('#listTitle').css("font-size", ".34rem");
                router.$('#cateTab').css("font-size", ".34rem");
                router.$('#tip-hd').css("font-size", ".26rem");
                router.$('#weixin').css("font-size", ".32rem");
                router.$('#dh').css("font-size", ".32rem");
                router.$('#youxiang').css("font-size", ".32rem");
                router.$('#title1').css("font-size", ".4rem");
                router.$('#plScrollListK').css("font-size", ".3rem");
            } else {
                router.$("#gz").css("font-size", ".23rem")
                router.$("#fb").css("font-size", ".23rem")
                router.$("#sy").css("font-size", "0.23rem")
                router.$("#name1").css("font-size", "0.23rem")
                router.$('#listTitle').css("font-size", ".26rem");
                router.$('#cateTab').css("font-size", ".26rem");
                router.$('#tip-hd').css("font-size", ".18rem");
                router.$('#weixin').css("font-size", ".26rem");
                router.$('#dh').css("font-size", ".26rem");
                router.$('#youxiang').css("font-size", ".26rem");
                router.$('#title1').css("font-size", ".32rem");
                router.$('#plScrollListK').css("font-size", ".22rem");
            }
            let languageArr = storage.get('languageArr',0)
            let html = ''
            let html2 = '<select class="languageSelect" id="languageSelectId">\n'
            if (language !== 'chinese_simplified' && language !== 'english') {
                languageArr.forEach(lan => {
                    if (lan.id === language) {
                        html += '<span class="language" id="'+lan.id+'">'+lan.name+'</span>|'
                    } else {
                        html2 += '<option value="'+lan.id+'">'+lan.name+'</option>'
                    }
                })
            } else {
                languageArr.forEach(lan => {
                    html2 += '<option value="'+lan.id+'">'+lan.name+'</option>'
                })
            }
            html+= '<span class="language" id="english">English</span>|<span class="language" id="chinese_simplified">简体中文</span>'
            router.$("#languageContent").html(html + html2 + "</select>")
            router.$("#languageSelectId").val('')

            router.$(".language").click(function () {
                let selectId = $(this).attr('id')
                if (selectId !== language) {
                    storage.set("language", selectId)
                    location.reload()
                }
            })
            router.$("#languageSelectId").change(function () {
                let selectId = $(this).val()
                if (selectId !== language) {
                    storage.set("language", selectId)
                    location.reload()
                }
            })

            let uiLoadingSc = bui.loading({
                appendTo:"#loading",
                width: 40,
                height: 40,
                opacity: 0.5,
                autoClose: false,
                text:"生成中。。。"
            });
            let uiLoading = bui.loading({
                appendTo:"#loading",
                width: 40,
                height: 40,
                opacity: 0.5,
                autoClose: false,
                text:"加载中。。。"
            });
            // uiLoading.show()

            let showFlag = false
            let page = 1
            router.$("#articleMenu").hide()

            // 自定义居中弹出框
            let lookDialog = bui.dialog({
                id: "#lookDialog",
                fullscreen: true,
                mask: true
            });
            router.$('#lookDialog').click(function () {
                lookDialog.close()
            })

            // window.addEventListener('popstate', function(e) { //回调函数中实现需要的功能
            //     storage.set("tzPage", 0)
            //     router.replace({url: "pages/mainIndex/mainIndex.html"});
            // }, false);

            const url = window.location.href
            let artile;
            let glUserid = ''
            let params = module.props;
            if ((params && params.id != undefined) || url.indexOf("?") > -1) {
                if (!params && params.id == undefined) {
                    let param = url.split("?")[1]
                    let params = param.split("&")
                    let id = params[0].split("=")[1]
                    let gl= params[1].split("=")[1]
                    if (gl && gl != 'null') {
                        glUserid = gl
                    }
                    artile = {id:id, glUserid: glUserid}
                } else {
                    artile = module.props;
                    if (artile.glUserid && artile.glUserid != 'null') {
                        glUserid = artile.glUserid
                    }
                }
                if (params.tzSign == '0') {
                    router.$("#articleFh").click(function () {
                        let prevInfo = bui.history.getCurrentPrev()
                        router.replace({url: prevInfo.url});
                    })
                } else {
                    router.$("#articleFh").click(function () {
                        storage.set("tzPage", 0)
                        router.replace({url: "pages/mainIndex/mainIndex.html"});
                    })
                }
            }
            if (!artile) {
                artile = storage.get('articleInfo',0)
                if (artile.glUserid && artile.glUserid != 'null') {
                    glUserid = artile.glUserid
                }
                router.$("#articleFh").click(function (){
                    storage.set("tzPage", 0)
                    router.replace({url: "pages/mainIndex/mainIndex.html"});
                })
            }

            router.$("#sy").click(function (){
                storage.set("tzPage", 0)
                router.replace({url: "pages/mainIndex/mainIndex.html"});
                // router.load({url: "pages/mainIndex/mainIndex.html", replace: true, firstAnimate: true, autoInit: false});
            })

            let lyTotal = 0
            let userId = ''
            let token = storage.get("token", 0)
            let user = storage.get("user", 0)
            if (user && user.userId && user.userId !== 'undefined') {
                userId = user.userId
            }

            //加载文章详情
            let articleInfo = storage.get("articleInfo" + artile.id,0)
            if (articleInfo) {
                if (articleInfo.delFlag == '1') {
                    router.$("#gqSign").show()
                } else {
                    router.$("#gqSign").hide()
                }

                if (articleInfo.iscomment == "0") {
                    router.$("#lyK").hide()
                }

                router.$("#name1").html(articleInfo.cateStr)
                router.$("#cateTab").html(articleInfo.cateStr+"信息")
                router.$("#time").html(formatDate(articleInfo.ptime) + " 发布")
                router.$("#country2").html(articleInfo.countryStr + " "+ articleInfo.cityStr)

                if (articleInfo.tel) {
                    router.$("#phone").html(articleInfo.tel)
                    router.$("#dh").show()
                    router.$("#phoneBtn").attr("href","tel:" + articleInfo.tel)
                    router.$("#phoneBtn").show()

                    router.$("#articleTel").attr("href","tel:" + articleInfo.tel)
                }
                router.$("#articleTel").click(function () {
                    if (!articleInfo.tel) {
                        bui.alert("发布者未填写手机号信息！")
                    }
                })
                router.$("#copy").click(function () {
                    if(articleInfo.wx) {
                        new ClipboardJS('.btn',{text:function(trigger) { return articleInfo.wx;} });
                        bui.alert("复制成功！")
                    } else {
                        bui.alert("发布者未填写微信号信息！")
                    }
                })
                if (articleInfo.wx) {
                    router.$("#wx").html(articleInfo.wx)
                    router.$("#weixin").show()
                }
                if (articleInfo.concat) {
                    router.$("#concat").html(articleInfo.concat)
                    router.$("#lxr").show()
                }
                if (articleInfo.concat) {
                    router.$("#address").html(articleInfo.adress)
                    router.$("#addressK").show()
                }
                if (articleInfo.email) {
                    router.$("#email").html(articleInfo.email)
                    router.$("#youxiang").show()
                }

                if (!articleInfo.title1)  {
                    router.$("#bt").html(articleInfo.title)
                    router.$("#title1").html(articleInfo.title)
                    router.$("#title1").show()
                } else {
                    router.$("#bt").html(articleInfo.title1)
                    router.$("#title1").html(articleInfo.title1)
                    router.$("#title1").show()
                }
                let cont = articleInfo.content
                if (cont && cont.indexOf("<img") > -1) {
                    let urls = getMatchString(cont);
                    urls.forEach(url => {
                        let content2 = url.split("src=\"")[1];
                        content2 = content2.substring(0,content2.length -1);
                        if (content2.indexOf("http:") < 0 && content2.indexOf("https:") < 0) {
                            if (content2.indexOf("/ueditor") > -1) {
                                cont = cont.replace(content2, "https://ty.happindo.com/prod-api/profileOld" + content2);
                            } else if(content2.indexOf("/profile") > -1) {
                                let dev = content2.split("/profile");
                                cont = cont.replace(content2, "http://58hw.oss-cn-beijing.aliyuncs.com" + dev[1]);
                            }
                        }
                    })
                }
                if (articleInfo.oldSign === "0" && articleInfo.imgCs) {
                        let arr = articleInfo.imgCs.split(",")
                        for (let i = 0; i < arr.length; i++) {
                            if (arr[i].indexOf("http:") > -1 || arr[i].indexOf("https:") > -1) {
                                cont += "<img src=\"" + arr[i] + "\" style=\"width: 300px; 150px\">"
                            } else {
                                cont += "<img src=\"http://58hw.oss-cn-beijing.aliyuncs.com" + arr[i] + "\" style=\"width: 300px; 150px\">"
                            }
                        }
                }
                router.$("#content1").html(cont)

                router.$("#content1 img").click(function () {
                    let url = $(this).attr("src")
                    router.$("lookImg").attr("src", url)
                    lookDialog.open()
                })

                uiLoading.stop()
                try {
                    translate.execute();
                }catch (e) {
                    console.log("切换语言报错")
                }
            }

            // let ks = new Date().getTime()
            //1、创建ajax引擎对象 ---- 所有的操作都是通过引擎对象
            let xmlHttp = new XMLHttpRequest();
            //2、绑定监听 ---- 监听服务器是否已经返回相应数据
            xmlHttp.onreadystatechange = function(){
                let res = xmlHttp.response
                if (res) {
                    res = eval('(' + res + ')')
                    let data = res.data

                    router.$("#typeStr").html(data.cateStr)
                    router.$("#position").html(data.cityStr)
                    router.$("#avater").attr("src", data.avater)
                    router.$("#userName").html(data.userStr)
                    router.$("#timeCity").html(formatDate(data.ptime) + "  " + data.cateStr)

                    if (data.contentText) {
                        if (data.contentText.length > 100) {
                            router.$("#articleContent").html(data.contentText.substring(0,100) + '...')
                            router.$("#lookQw").show()
                        } else {
                            router.$("#articleContent").html(data.contentText)
                            router.$("#lookQw").hide()
                        }
                    } else {
                        router.$("#articleContent").html(data.title)
                        router.$("#lookQw").hide()
                    }

                    if (data.imgCs){
                        router.$("#imgs2").show()
                        let imgArr = data.imgCs.split(',')
                        let len = imgArr.length > 3 ? 3 : imgArr.length
                        let html = ''
                        for (let i = 0; i < len; i++) {
                            if (i === 0) {
                                html +=  '                                    <div class="span1 '+picClass+'" style="padding-left: 0">\n'
                            } else {
                                html +=  '                                    <div class="span1 '+picClass+'">\n'
                            }

                            html += '                                        <img src="'+imgArr[i]+'?x-oss-process=style/index" alt="">\n' +
                                '                                    </div>\n'
                        }

                        if (len < 3) {
                            for (let i = 0; i < 3- len; i++) {
                                html +=  '                                    <div class="span1 '+picClass+'">\n' +
                                    '                                    </div>\n'
                            }
                        }
                        router.$("#imgs2").html(html)
                    }

                    // let js = new Date().getTime()
                    // bui.alert("前端访问结束时间：" + (js-ks) +"\n后端访问结束时间：" + data.sj)
                    if (data.delFlag == '1') {
                        router.$("#gqSign").show()
                    } else {
                        router.$("#gqSign").hide()
                    }

                    if (data.iscomment == "0") {
                        router.$("#lyK").hide()
                    }

                    router.$("#name1").html(data.cateStr)

                    router.$("#cateTab").html(data.cateStr+"信息")
                    router.$("#time").html(formatDate(data.ptime) + " 发布")
                    router.$("#country2").html(data.countryStr + " "+ data.cityStr)
                    // if (data.userStr) {
                    //     router.$("#concat").html(data.userStr)
                    //     router.$("#lxr").show()
                    // }
                    if (data.tel) {
                        router.$("#phone").html(data.tel)
                        router.$("#dh").show()
                        router.$("#phoneBtn").attr("href","tel:" + data.tel)
                        router.$("#phoneBtn").show()

                        router.$("#articleTel").attr("href","tel:" + data.tel)
                    }
                    if (data.concat) {
                        router.$("#concat").html(data.concat)
                        router.$("#lxr").show()
                    }
                    if (data.adress) {
                        router.$("#address").html(data.adress)
                        router.$("#addressK").show()
                    }
                    router.$("#articleTel").click(function () {
                        if (!data.tel) {
                            bui.alert("发布者未填写手机号信息！")
                        }
                    })
                    router.$("#copy").click(function () {
                        if(data.wx) {
                            new ClipboardJS('.btn',{text:function(trigger) { return data.wx;} });
                            bui.alert("复制成功！")
                        } else {
                            bui.alert("发布者未填写微信号信息！")
                        }
                    })
                    if (data.wx) {
                        router.$("#wx").html(data.wx)
                        router.$("#weixin").show()
                    }
                    if (data.email) {
                        router.$("#email").html(data.email)
                        router.$("#youxiang").show()
                    }

                    if (!data.title1)  {
                        router.$("#bt").html(data.title)
                        router.$("#title1").html(data.title)
                        router.$("#title1").show()
                    } else {
                        router.$("#bt").html(data.title1)
                        router.$("#title1").html(data.title1)
                        router.$("#title1").show()
                    }
                    router.$("#content1").html(data.content)

                    router.$("#content1 img").click(function () {
                        let url = $(this).attr("src")
                        router.$("lookImg").attr("src", url)
                        lookDialog.open()
                    })
                    try {
                        translate.execute();
                    }catch (e) {
                        console.log("切换语言报错")
                    }
                }
            }
            if (artile.id && artile.id !== 'undefined') {
                //3、绑定地址
                xmlHttp.open("POST",global.api.getAdvertiseInfo,false);
                //4、发送请求
                xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                xmlHttp.send("id=" + artile.id);
            }


            //加载文章详情（其它数据）
            if (artile.id && artile.id !== 'undefined') {
                bui.ajax({
                    url: global.api.getAdvertiseInfoOther,
                    data: {id: artile.id, user: userId},
                    method: "POST"
                }).then(function(res){
                    let data = res.data

                    if (data) {
                        if (data.cateCount > 0) {
                            if (data.cateCount > 99) {
                                router.$("#cateCount").html('99+')
                                router.$("#cateCount").show()
                            } else {
                                router.$("#cateCount").html(data.cateCount)
                                router.$("#cateCount").show()
                            }
                        }

                        let shareImage = data.shareImage
                        if (!shareImage) {
                            shareImage = 'https://ty.happindo.com/prod-api/profileOld/logo.png'
                        }
                        console.log("分享的图片==============")
                        console.log("分享的图片==============")
                        console.log("分享的图片==============")
                        console.log(shareImage)

                        if (data.qrcode) {
                            router.$("#glyQrcodeK").show()
                            router.$("#qrcode2").attr('src', data.qrcode)
                        }

                        if (data.userFooter) {
                            router.$("#articleFooter").html(data.userFooter)
                            router.$("#articleFooter").show()
                        }

                        storage.set("org",data.org)
                        router.preload([
                            {
                                url: "pages/mainIndex/mainIndex.html",
                            }
                        ]);
                        org = data.org
                        if (org.qrcode) {
                            router.$("#qrcode1").attr('src', org.qrcode)
                        } else {
                            router.$("#qrcode1").attr('src', 'images/qrcode.jpg')
                        }
                        router.$("#name1").click(function () {
                            storage.set('menCate', data.cate + '-' + data.cateStr + '-' + org.id)
                            storage.set('tzArticleInfo', artile)
                            // router.load({ url: "pages/flPage/flPage.html",param:{tzSign: '1'}});
                            router.load({ url: "pages/flPage/flPage.html"});
                        })

                        //查询菜单
                        bui.ajax({
                            url: global.api.getMenuList,
                            data: {city: org.id, country: org.parent, place: '1'},
                            method: "POST"
                        }).then(function(res){
                            let menuData = res.data
                            storage.set("menu" + org.id, menuData)
                        })


                        if (token) {
                            bui.ajax({
                                url: global.api.verifyToken,
                                method: "POST",
                                headers: {Token: token}
                            }).then(function(res){
                                if (res.code != '200') {
                                    router.$("#lyText").attr("placeholder", "请登录再留言")
                                    router.$("#lyText").click(function () {
                                        // 修改数据
                                        bui.confirm("留言需要先登录后才可操作，确定要登录么？", function(e) {
                                            //this 是指点击的按钮
                                            let text = router.$(e.target).text();
                                            if (text == "确定") {
                                                storage.set('tzArticleInfo', artile)
                                                storage.set("articleInfo", artile)
                                                storage.set("dlTz", '1')
                                                router.replace({ url: "pages/login/login.html", param:{tzSign: '1'}});
                                            }
                                            this.close()
                                        });
                                    })
                                    //留言
                                    router.$("#lyBtn").click(function () {
                                        // 修改数据
                                        bui.confirm("留言需要先登录后才可操作，确定要登录么？", function(e) {
                                            //this 是指点击的按钮
                                            let text = router.$(e.target).text();
                                            if (text == "确定") {
                                                storage.set('tzArticleInfo', artile)
                                                storage.set("articleInfo", artile)
                                                storage.set("dlTz", '1')
                                                router.replace({ url: "pages/login/login.html", param:{tzSign: '1'}});
                                            }
                                            this.close()
                                        });
                                    })
                                } else {
                                    router.$("#lyText").attr("placeholder", "请输入留言")
                                    //留言
                                    router.$("#lyBtn").click(function () {
                                        let ly = router.$("#lyText").val()
                                        if (ly) {
                                            uiLoading.show()
                                            bui.ajax({
                                                url: global.api.insertComment,
                                                data: {pid: artile.id,content: ly,city: org.name, cityId: org.id, country: org.parent},
                                                method: "POST",
                                                headers: {Token: token}
                                            }).then(function(res){
                                                uiLoading.stop()
                                                if (res.code == '200') {
                                                    if (res.data == '1') {
                                                        bui.confirm({
                                                            "title": "",
                                                            "height": 300,
                                                            "content": '<div class="bui-box-center"><p>留言成功，请查看！</p></div>',
                                                            "buttons": ["确定"],
                                                            callback: function(e) {
                                                                //this 是指点击的按钮
                                                                let text = router.$(e.target).text();

                                                                if (text == "确定") {
                                                                    page = 1
                                                                    lyTotal = 0
                                                                    router.$("#lyText").val('')
                                                                    router.$("#plScrollList").html('')
                                                                    if (artile.id) {
                                                                        //加载网友留言
                                                                        bui.ajax({
                                                                            url: global.api.commentList,
                                                                            data: {pid: artile.id, page: page, limit: 3},
                                                                            method: "POST"
                                                                        }).then(function(res){
                                                                            let lyData = res.data

                                                                            let html = ""
                                                                            if (lyData && lyData.length > 0) {
                                                                                router.$("#plScrollListK").show()

                                                                                $.each(lyData, function (index, el) {
                                                                                    lyTotal++
                                                                                    html += '<div class="bui-btn" style="height: 1.1rem">\n' +
                                                                                        '                            <div>\n' +
                                                                                        '                                <div style="float: left;">\n' +
                                                                                        '                                    <img src="'+el.avatar+'" style="width: 22px; height: 22px; border-radius: 100%">\n' +
                                                                                        '                                </div>\n' +
                                                                                        '                                <div style="float: left;margin-top: 3px;margin-left: 5px;font-size: 0.24rem" class="item-text">'+el.userStr+'</div>\n' +
                                                                                        '                            </div>\n' +
                                                                                        '                           <p class="lyText">'+el.content+'</p>\n' +
                                                                                        '                        </div>'
                                                                                })

                                                                                if (lyTotal < res.total) {
                                                                                    router.$("#loadMore").show()
                                                                                }
                                                                            }
                                                                            router.$("#plScrollList").html(html)
                                                                        })
                                                                    }
                                                                }
                                                                this.close()
                                                            }
                                                        });
                                                    } else {
                                                        router.$("#lyText").val('')
                                                        // 修改数据
                                                        bui.alert("留言成功，等待审核！")
                                                    }
                                                } else {
                                                    bui.alert("留言失败！")
                                                }
                                            })
                                        } else {
                                            bui.alert("请输入留言内容");
                                        }
                                    })
                                }
                            })
                        } else {
                            router.$("#lyText").attr("placeholder", "请登录再留言")
                            router.$("#lyText").click(function () {
                                // 修改数据
                                bui.confirm("留言需要先登录后才可操作，确定要登录么？", function(e) {
                                    //this 是指点击的按钮
                                    let text = router.$(e.target).text();
                                    if (text == "确定") {
                                        storage.set('tzArticleInfo', artile)
                                        storage.set("articleInfo", artile)
                                        storage.set("dlTz", '1')
                                        router.replace({ url: "pages/login/login.html", param:{tzSign: '1'}});
                                    }
                                    this.close()
                                });
                            })
                            //留言
                            router.$("#lyBtn").click(function () {
                                // 修改数据
                                bui.confirm("留言需要先登录后才可操作，确定要登录么？", function(e) {
                                    //this 是指点击的按钮
                                    let text = router.$(e.target).text();
                                    if (text == "确定") {
                                        storage.set('tzArticleInfo', artile)
                                        storage.set("articleInfo", artile)
                                        storage.set("dlTz", '1')
                                        router.replace({ url: "pages/login/login.html", param:{tzSign: '1'}});
                                    }
                                    this.close()
                                });
                            })
                        }

                        //加载广告
                        bui.ajax({
                            url: global.api.getAdvertiseDetailList,
                            data: {city: org.id, redisCity: org.name,country: org.parent, userId: glUserid},
                            method: "POST"
                        }).then(function(res){
                            let ggArr = res.data

                            let arr = []

                            if (ggArr && ggArr.length > 0) {
                                let len = ggArr.length

                                let index = 0
                                if (len > 1) {
                                    index = Math.floor(Math.random()*ggArr.length)
                                    arr.push(index)
                                }
                                router.$("#advertise1").attr("src", ggArr[index].imgUrl)
                                router.$("#advertise1").attr("name", ggArr[index].article + '~' + ggArr[index].title)
                                router.$("#advertise1").show()

                                if (len > 1) {
                                    index = Math.floor(Math.random()*ggArr.length)
                                    while (arr.indexOf(index) > -1) {
                                        index = Math.floor(Math.random()*ggArr.length)
                                        if (arr.indexOf(index) === -1) {
                                            arr.push(index)
                                            break;
                                        }
                                    }
                                    router.$("#advertise12").attr("src", ggArr[index].imgUrl)
                                    router.$("#advertise12").attr("name", ggArr[index].article + '~' + ggArr[index].title)
                                    router.$("#advertise12").show()
                                }

                                if (len > 2) {
                                    router.$("#ggk").show()

                                    if (len > 2) {
                                        index = Math.floor(Math.random()*ggArr.length)
                                        while (arr.indexOf(index) > -1) {
                                            index = Math.floor(Math.random()*ggArr.length)
                                            if (arr.indexOf(index) === -1) {
                                                arr.push(index)
                                                break;
                                            }
                                        }
                                        router.$("#advertise2").attr("src", ggArr[index].imgUrl)
                                        router.$("#advertise2").attr("name", ggArr[index].article + '~' + ggArr[index].title)
                                        router.$("#advertise2").show()
                                    }

                                    if (len > 3) {
                                        index = Math.floor(Math.random()*ggArr.length)
                                        while (arr.indexOf(index) > -1) {
                                            index = Math.floor(Math.random()*ggArr.length)
                                            if (arr.indexOf(index) === -1) {
                                                arr.push(index)
                                                break;
                                            }
                                        }
                                        router.$("#advertise3").attr("src", ggArr[index].imgUrl)
                                        router.$("#advertise3").attr("name", ggArr[index].article + '~' + ggArr[index].title)
                                        router.$("#advertise3").show()
                                    }

                                    if (len > 4) {
                                        index = Math.floor(Math.random()*ggArr.length)
                                        while (arr.indexOf(index) > -1) {
                                            index = Math.floor(Math.random()*ggArr.length)
                                            if (arr.indexOf(index) === -1) {
                                                arr.push(index)
                                                break;
                                            }
                                        }
                                        router.$("#advertise4").attr("src", ggArr[index].imgUrl)
                                        router.$("#advertise4").attr("name", ggArr[index].article + '~' + ggArr[index].title)
                                        router.$("#advertise4").show()
                                    }
                                }
                            }
                        })

                        router.$("#listTitle1").html(org.description+data.cateStr)
                        //查询及时快报
                        if (data.id !== 'undefined' && data.cate !== 'undefined' && data.cate !== 'null') {
                            ids = []
                            bui.list({
                                id: "#scrollList1",
                                url: global.api.getArticleList,
                                pageSize: 10, // 当pageSize 小于返回的数据大小的时候,则认为是最后一页,接口返回的数据最好能返回空数组,而不是null
                                data: {
                                    id: data.id,
                                    city: org.id,
                                    country: org.parent,
                                    redisCity: org.name,
                                    isduplicate: 0,
                                    "cate": data.cate
                                },
                                //如果分页的字段名不一样,通过field重新定义
                                field: {
                                    page: "page",
                                    size: "limit",
                                    data: "data"
                                },
                                callback: function(e) {
                                    // e.target 为你当前点击的元素
                                    // e.currentTarget 为你当前点击的handle 整行
                                    let id = router.$(e.currentTarget).attr("id")
                                    if (id) {
                                        let glUserid = router.$(e.currentTarget).attr("name")
                                        // storage.set("articleId", {id: id, glUserid: glUserid})
                                        router.load({ url: "pages/articleInfo/articleInfo.html", param: {tzSign: '0',id: id, glUserid: glUserid}});
                                    }
                                },
                                template: function(data) {
                                    let fontSize = '0.3rem'
                                    let fontSize2 = '0.24rem'
                                    if (language !== "chinese_simplified") {
                                        fontSize = '0.22rem'
                                        fontSize2 = '0.18rem'
                                    }

                                    var html = "";
                                    let newIds = []
                                    data.forEach(function(el, index) {
                                        if (ids.indexOf(el.id) === -1){
                                            newIds.push(el.id)
                                            html += '<li class="bui-btn bui-box" id="'+el.id+'" name="'+el.glUserid+'">\n' +
                                                '                            <div class="span1">\n'

                                            if (el.zd == '0') {
                                                html += '                                <div class="zdK" style="font-size: '+fontSize+'">荐</div><p style="color: red;font-size: '+fontSize+'">'+el.title+'</p>\n'
                                            } else {
                                                html += '                                <p style="color: black;font-size: '+fontSize+'">'+el.title+'</p>\n'
                                            }

                                            html += '                                <p class="item-text">\n' +
                                                '                                    <span class="listTab" style="font-size: '+fontSize2+'">'+el.cateStr+'</span>\n' +
                                                '                                    <span style="font-size: '+fontSize2+'">\n' + formatDate(el.ptime) +
                                                '                                    </span>\n' +
                                                '                                </p>\n' +
                                                '                            </div>\n'
                                            html += '                        </li>'
                                        }
                                    });
                                    ids = newIds

                                    setTimeout(function () {
                                        try {
                                            translate.execute();
                                        }catch (e) {
                                            console.log("切换语言报错")
                                        }
                                    },1000)
                                    return html;
                                }
                            })
                        }


                        let showTitile;
                        if (data.title) {
                            showTitile = data.title
                        } else {
                            showTitile = data.title1
                        }
                        let contentText = ""
                        if (data.contentText){
                            contentText = data.contentText.replace(/[\r\n]/g,"").substring(0,50)
                        }

                        router.$("#ogTitle").attr('content', showTitile)
                        router.$("#ttTitle").attr('content', showTitile)
                        router.$("#ogDesc").attr('content', contentText)
                        router.$("#ttDesc").attr('content', contentText)
                        router.$("#ogImg").attr('content', shareImage)
                        router.$("#ttImg").attr('content', shareImage)

                        router.$("#wb").click(function () {
                            let appkey = '你的Appkey';
                            WB2.anyWhere(function(W) {
                                W.widget.publish({
                                    'source': appkey,
                                    'url': 'https://ty.happindo.com/#pages/articleInfo/articleInfo?id='+artile.id + "&glUserid=" + artile.glUserid,
                                    'title': showTitile,
                                    'pic': shareImage
                                });
                            });
                        })
                        router.$("#facebook").click(function () {
                            let url = encodeURIComponent('https://ty.happindo.com/#pages/articleInfo/articleInfo?id='+artile.id + "&glUserid=" + artile.glUserid)
                            let facebook = `https://www.facebook.com/sharer/sharer.php?u=${url}`
                            window.open(facebook,'_blank')
                        })
                        router.$("#tt").click(function () {
                            let url = encodeURIComponent('https://ty.happindo.com/#pages/articleInfo/articleInfo?id='+artile.id + "&glUserid=" + artile.glUserid)
                            let text = `${showTitile} ${url}&via=`
                            let twitter = `https://twitter.com/intent/tweet?text=${text}`
                            window.open(twitter,'_blank')
                        })
                        // router.$("#scrollList1").unbind()

                        if (isWeiXin()) {
                            console.log('设置微信分享=================')
                            //获取微信配置
                            bui.ajax({
                                url: global.api.getWxConfig,
                                data: {url: location.href.split('#')[0]},
                                method: "GET"
                            }).then(function(res){
                                if (res.code == '200') {
                                    let dat = res.data

                                    wx.config({
                                        debug: false,
                                        appId: dat.appId,
                                        timestamp: dat.timestamp,
                                        nonceStr: dat.nonceStr,
                                        signature: dat.signature,
                                        jsApiList: ["updateTimelineShareData", "updateAppMessageShareData", "onMenuShareTimeline", "onMenuShareAppMessage"]
                                    })
                                    wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
                                        wx.onMenuShareAppMessage({
                                            title: '【海外同城】' + showTitile, // 分享标题
                                            desc: contentText, // 分享描述
                                            link: 'https://ty.happindo.com/#pages/articleInfo/articleInfo?id='+artile.id + "&glUserid=" + artile.glUserid + "&nonce=" + translate.generateRandomString(4), // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                            imgUrl: shareImage, // 分享图标
                                            type: '', // 分享类型,music、video或link，不填默认为link
                                            dataUrl: '',
                                            success: function () {
                                            }
                                        })
                                        wx.onMenuShareTimeline({
                                            title: '【海外同城】' + showTitile.substring(0,40), // 分享标题
                                            desc: contentText, // 分享描述
                                            link: 'https://ty.happindo.com/#pages/articleInfo/articleInfo?id='+artile.id + "&glUserid=" + artile.glUserid + "&nonce=" + translate.generateRandomString(4), // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                            imgUrl: shareImage, // 分享图标
                                            success: function () {
                                            }
                                        })
                                    });
                                } else {
                                    // bui.alert(res.msg)
                                }
                            })
                        }
                    } else {
                        bui.confirm({
                            "title": "",
                            "height": 460,
                            "content": '<div class="bui-box-center"><div><h3>当前文章已消失！</h3></div></div>',
                            "buttons": [{ name: "确定", className: "primary-reverse" }],
                            callback:function(){
                                this.close();
                                bui.back()
                            }
                        });
                    }
                })
            }


            // 自定义居中弹出框
            let gzDialog = bui.dialog({
                id: "#gzDialog1",
                height: 300,
                // mask: false,
                callback: function(e) {}
            });
            router.$("#gz").click(function () {
                gzDialog.open()
            })
            router.$("#fb").click(function () {
                storage.set('tzArticleInfo', artile)
                if (token) {
                    bui.ajax({
                        url: global.api.verifyToken,
                        method: "POST",
                        headers: {Token: token}
                    }).then(function(res){
                        if (res.code != '200') {
                            storage.set("dlTz", '0')
                            router.replace({ url: "pages/login/login.html", param:{tzSign: '1'}});
                        } else {
                            router.load({ url: "pages/fbZj/fbZj.html",param:{tzSign: '1'}});
                        }
                    })
                } else {
                    storage.set("dlTz", '0')
                    router.replace({ url: "pages/login/login.html", param:{tzSign: '1'}});
                }
            })

            router.$(".advert").click(function () {
                let param = router.$(this).attr("name")
                let params = param.split('~')
                let id = params[0]
                let glUserid = params[1]
                router.load({ url: "pages/articleInfo/articleInfo.html", param: {id: id, glUserid: glUserid}});
                // storage.set("article", param)
                // bui.load({ url: "pages/home/index.html"});
            })

            //加载网友留言
            if (artile.id) {
                bui.ajax({
                    url: global.api.commentList,
                    data: {pid: artile.id, page: page, limit: 3},
                    method: "POST"
                }).then(function(res){
                    let lyData = res.data

                    let html = ""
                    if (lyData && lyData.length > 0) {
                        router.$("#plScrollListK").show()

                        $.each(lyData, function (index, el) {
                            lyTotal++
                            html += '<div class="bui-btn" style="height: 1.1rem">\n' +
                                '                            <div>\n' +
                                '                                <div style="float: left;">\n' +
                                '                                    <img src="'+el.avatar+'" style="width: 22px; height: 22px; border-radius: 100%">\n' +
                                '                                </div>\n' +
                                '                                <div style="float: left;margin-top: 3px;margin-left: 5px;font-size: 0.24rem" class="item-text">'+el.userStr+'</div>\n' +
                                '                            </div>\n' +
                                '                           <p class="lyText">'+el.content+'</p>\n' +
                                '                        </div>'
                        })

                        if (lyTotal < res.total) {
                            router.$("#loadMore").show()
                        }
                    }
                    router.$("#plScrollList").html(html)
                    try {
                        translate.execute();
                    }catch (e) {
                        console.log("切换语言报错")
                    }
                })
            }

            router.$("#loadMore").click(function () {
                page += 1
                if (artile.id) {
                    bui.ajax({
                        url: global.api.commentList,
                        data: {pid: artile.id, page: page, limit: 3},
                        method: "POST"
                    }).then(function(res){
                        let lyData = res.data

                        let html = ""
                        if (lyData && lyData.length > 0) {
                            $.each(lyData, function (index, el) {
                                lyTotal++
                                html += '<div class="bui-btn" style="height: 1.1rem">\n' +
                                    '                            <div>\n' +
                                    '                                <div style="float: left;">\n' +
                                    '                                    <img src="'+el.avatar+'" style="width: 22px; height: 22px; border-radius: 100%">\n' +
                                    '                                </div>\n' +
                                    '                                <div style="float: left;margin-top: 3px;margin-left: 5px;font-size: 0.24rem" class="item-text">'+el.userStr+'</div>\n' +
                                    '                            </div>\n' +
                                    '                           <p class="lyText">'+el.content+'</p>\n' +
                                    '                        </div>'
                            })

                            if (lyTotal >= res.total) {
                                router.$("#loadMore").hide()
                            }
                        }
                        router.$("#plScrollList").append(html)
                    })
                }
            })

            //底部操作按钮
            router.$("#ly").click(function () {
                document.getElementById('lyK').scrollIntoView()
            })
            router.$("#gzMy").click(function () {
                gzDialog.open()
            })
            router.$("#lxfs").click(function () {
                if(showFlag) {
                    showFlag = false
                    router.$("#articleMenu").hide()
                } else {
                    showFlag = true
                    router.$("#articleMenu").show()
                }
            })

            // 自定义居中弹出框
            let scQrcodeDialog = bui.dialog({
                id: "#scQrcodeDialog",
                height: 490,
                // mask: false,
                callback: function(e) {}
            });
            router.$("#scHb").click(function () {
                uiLoadingSc.show()
                bui.ajax({
                    url: global.api.createQrcode,
                    data:{id: artile.id, url: 'https://ty.happindo.com/#pages/articleInfo/articleInfo?id='+ artile.id + "&glUserid=" + glUserid},
                    method: "POST"
                }).then(function(res){
                    let url = res.msg
                    // qrcodeName = id+"二维码.png"
                    router.$("#qrcode").attr('src', url)
                    router.$("#qrcodeHb").show()

                    html2canvas(router.$('#qrcodeHb')[0], {
                        useCORS: true, // 【重要】开启跨域配置
                        scale: window.devicePixelRatio < 3 ? window.devicePixelRatio : 2,
                        allowTaint: true, // 允许跨域图片
                    }).then((canvas) => {
                        qrcodeBase = canvas.toDataURL('image/jpeg', 1.0);

                        router.$("#qrcodeHb").hide()
                        router.$("#showQrcodePic").attr('src', qrcodeBase)
                        scQrcodeDialog.open()
                        uiLoadingSc.stop()
                    });
                })
            })

            // 自定义居中弹出框
            let shareDialog = bui.dialog({
                id: "#shareDialog",
                height: 160,
                // mask: false,
                callback: function(e) {}
            });
            router.$("#share").click(function () {
                shareDialog.open()
            })
        }
    };


    // 初始化
    pageview.init();

    // 输出模块
    return pageview;
})

function isWeiXin() {
    let ua = navigator.userAgent.toLowerCase()
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
        return true
    } else {
        return false
    }
}

function isMobile() {
    let userAgentInfo = navigator.userAgent;

    let mobileAgents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"];

    let mobile_flag = false;

    let ua = navigator.userAgent.toLowerCase()
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
        mobile_flag = true
    } else {
        //根据userAgent判断是否是手机
        for (let v = 0; v < mobileAgents.length; v++) {
            if (userAgentInfo.indexOf(mobileAgents[v]) > 0) {
                mobile_flag = true;
                break;
            }
        }
    }

    return mobile_flag;
}

function formatDate(time) {
    let date = new Date(time * 1000);
    // let now = new Date();
    // let days=parseInt((now - date) / (1000 * 60 * 60* 24) + '');
    // if (days > 7){
    let Y = date.getFullYear() + '-';
    let M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    let D = (date.getDate() < 10 ? '0'+(date.getDate()) : date.getDate()) + ' ';
    let h = (date.getHours() < 10 ? '0'+(date.getHours()) : date.getHours()) + ':';
    let m = (date.getMinutes() < 10 ? '0'+(date.getMinutes()) : date.getMinutes()) + ':';
    let s = (date.getSeconds() < 10 ? '0'+(date.getSeconds()) : date.getSeconds());
    return Y+M+D+h+m+s
    // } else if (days < 1) {
    //     let hour=parseInt((now - date) / (1000 * 60 * 60) + '');
    //     return hour + "小时前"
    // }
    // return days + "天前"
}

function getMatchString(content){
    let pics = []; // 因文件可能有多张图片，故用集合来存储结果
    let compile = /<img.*?(?:>|\/>)/gi;
    let compile2 = /[ ]src=[\'\"]?([^\'\"]*)[\'\"]/gi;

    let matcher = content.match(compile);
    matcher.forEach(img => {
        let matcher2 = img.match(compile2);
        if (matcher2.length > 0) {
            pics.push(matcher2[0].trim())
        }
    })
    return pics;
}
